<template>
  <el-dialog 
    :model-value="visible" 
    @update:model-value="$emit('update:visible', $event)"
    title="新建下载任务" 
    width="700px"
    :before-close="handleClose"
    class="new-task-dialog"
    top="8vh"
  >
    <div class="dialog-header">
      <div class="header-icon">
        <el-icon><Download /></el-icon>
      </div>
      <div class="header-content">
        <h3 class="dialog-title">新建下载任务</h3>
        <p class="dialog-subtitle">配置M3U8视频下载参数</p>
      </div>
    </div>

    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="140px"
      class="task-form"
    >
      <div class="form-section">
        <div class="section-header">
          <el-icon class="section-icon"><Link /></el-icon>
          <span class="section-title">基本信息</span>
        </div>
        
        <el-form-item label="M3U8 URL" prop="url">
          <el-input 
            v-model="form.url" 
            placeholder="请输入M3U8文件URL地址"
            clearable
            class="url-input"
            size="large"
          >
            <template #prepend>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            支持HTTP/HTTPS协议的M3U8播放列表文件
          </div>
        </el-form-item>

        <el-form-item label="文件名" prop="filename">
          <el-input 
            v-model="form.filename" 
            placeholder="请输入文件名（不含扩展名）"
            clearable
            class="filename-input"
            size="large"
          >
            <template #prepend>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            下载完成后将自动添加.mp4扩展名
          </div>
        </el-form-item>
      </div>

      <div class="form-section">
        <div class="section-header">
          <el-icon class="section-icon"><FolderOpened /></el-icon>
          <span class="section-title">下载设置</span>
        </div>
        
        <el-form-item label="下载位置" prop="outputPath">
          <div class="path-input-group">
            <el-input 
              v-model="form.outputPath" 
              placeholder="请选择下载保存位置"
              readonly
              class="path-input"
              size="large"
            >
              <template #prepend>
                <el-icon><FolderOpened /></el-icon>
              </template>
            </el-input>
            <el-button 
              @click="selectPath" 
              type="primary" 
              :icon="FolderOpened"
              class="select-btn"
              size="large"
            >
              选择路径
            </el-button>
          </div>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            选择下载文件的保存目录
          </div>
        </el-form-item>

        <el-form-item label="并发线程数" prop="concurrentThreads">
          <div class="number-input-group">
            <el-input-number 
              v-model="form.concurrentThreads" 
              :min="1" 
              :max="32"
              controls-position="right"
              class="number-input"
              size="large"
            />
            <span class="input-unit">线程</span>
          </div>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            建议设置为 4-16，数值越高下载速度越快，但可能影响系统性能
          </div>
        </el-form-item>

        <el-form-item label="重试次数" prop="maxRetries">
          <div class="number-input-group">
            <el-input-number 
              v-model="form.maxRetries" 
              :min="0" 
              :max="10"
              controls-position="right"
              class="number-input"
              size="large"
            />
            <span class="input-unit">次</span>
          </div>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            下载失败时的自动重试次数
          </div>
        </el-form-item>

        <el-form-item label="文件大小计算" prop="sizeCalculationMethod">
          <el-select 
            v-model="form.sizeCalculationMethod" 
            placeholder="选择文件大小计算方法"
            class="method-select"
            size="large"
          >
            <el-option label="自动选择" value="auto">
              <div class="option-content">
                <div class="option-title">自动选择</div>
                <div class="option-desc">系统自动选择最佳计算方法</div>
              </div>
            </el-option>
            <el-option label="基于时长估算" value="duration">
              <div class="option-content">
                <div class="option-title">基于时长估算</div>
                <div class="option-desc">根据视频时长和比特率估算文件大小</div>
              </div>
            </el-option>
            <el-option label="智能采样" value="sampling">
              <div class="option-content">
                <div class="option-title">智能采样</div>
                <div class="option-desc">采样少量分片计算平均大小</div>
              </div>
            </el-option>
            <el-option label="基于分片数量估算" value="estimate">
              <div class="option-content">
                <div class="option-title">基于分片数量估算</div>
                <div class="option-desc">根据分片数量快速估算文件大小</div>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">
            <el-icon><InfoFilled /></el-icon>
            选择计算下载文件总大小的方法，影响进度显示的准确性
          </div>
        </el-form-item>
      </div>

      
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div class="footer-left">
          <el-button 
            @click="handleReset" 
            type="warning" 
            :icon="Refresh"
            class="reset-btn"
          >
            重置表单
          </el-button>
        </div>
        <div class="footer-right">
          <el-button 
            @click="handleClose" 
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            @click="handleSubmit" 
            type="primary" 
            :loading="submitting"
            :icon="Download"
            class="submit-btn"
          >
            开始下载
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useTaskStore } from '../stores/taskStore'
import { useSettingsStore } from '../stores/settingsStore'
import { ElMessage } from 'element-plus'
import { 
  Download, 
  Link, 
  Document, 
  FolderOpened, 
  Setting, 
  Refresh, 
  InfoFilled 
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'task-created'])

const taskStore = useTaskStore()
const settingsStore = useSettingsStore()

const formRef = ref()
const submitting = ref(false)

// 表单数据
const form = reactive({
  url: '',
  filename: '',
  outputPath: '',
  concurrentThreads: 8,
  maxRetries: 3,
  sizeCalculationMethod: 'auto',
  autoStart: true,
  showProgress: true
})

// 表单验证规则
const rules = {
  url: [
    { required: true, message: '请输入M3U8 URL', trigger: 'blur' },
    { 
      pattern: /^https?:\/\/.+\.m3u8(\?.*)?$/i, 
      message: '请输入有效的M3U8文件URL', 
      trigger: 'blur' 
    }
  ],
  filename: [
    { required: true, message: '请输入文件名', trigger: 'blur' },
    { min: 1, max: 100, message: '文件名长度在1到100个字符', trigger: 'blur' }
  ],
  outputPath: [
    { required: true, message: '请选择下载位置', trigger: 'change' }
  ],
  concurrentThreads: [
    { required: true, message: '请设置并发线程数', trigger: 'change' },
    { type: 'number', min: 1, max: 32, message: '线程数在1到32之间', trigger: 'change' }
  ],
  maxRetries: [
    { required: true, message: '请设置重试次数', trigger: 'change' },
    { type: 'number', min: 0, max: 10, message: '重试次数在0到10之间', trigger: 'change' }
  ]
}

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadDefaultSettings()
  }
})

// 加载默认设置
const loadDefaultSettings = async () => {
  try {
    // 直接使用settingsStore.settings而不是getSettings方法
    const settings = settingsStore.settings
    form.outputPath = settings.defaultDownloadPath || ''
    form.concurrentThreads = settings.defaultConcurrentThreads || 8
    form.maxRetries = settings.defaultRetryCount || 3
    form.autoStart = settings.autoStartDownload !== false
    form.showProgress = settings.showDownloadSpeed !== false
  } catch (error) {
    console.error('加载默认设置失败:', error)
  }
}

// 选择下载路径
const selectPath = async () => {
  try {
    const result = await window.electronAPI.selectDirectory()
    if (result.success) {
      form.outputPath = result.data.path
      ElMessage.success('下载路径已设置')
    }
  } catch (error) {
    ElMessage.error('选择路径失败: ' + error.message)
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  loadDefaultSettings()
  ElMessage.info('表单已重置')
}

// 关闭对话框
const handleClose = () => {
  if (submitting.value) {
    ElMessage.warning('正在提交，请稍候...')
    return
  }
  
  formRef.value?.resetFields()
  emit('update:visible', false)
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return
    
    submitting.value = true
    
    // 创建任务
    const task = await taskStore.createTask({
      url: form.url,
      filename: form.filename,
      outputPath: form.outputPath,
      concurrentThreads: form.concurrentThreads,
      maxRetries: form.maxRetries,
      sizeCalculationMethod: form.sizeCalculationMethod,
      autoStart: form.autoStart
    })
    
    ElMessage.success('任务创建成功')
    emit('task-created', task)
    emit('update:visible', false)
    
    // 重置表单
    formRef.value?.resetFields()
    
  } catch (error) {
    ElMessage.error('创建任务失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadDefaultSettings()
})
</script>

<style scoped>
.new-task-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.new-task-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.new-task-dialog :deep(.el-dialog__header) {
  display: none;
}

.new-task-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.new-task-dialog :deep(.el-dialog__footer) {
  padding: 0;
}

/* 对话框头部 */
.dialog-header {
  background: #409eff;
  padding: 24px;
  color: #ffffff;
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.header-content {
  flex: 1;
}

.dialog-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  line-height: 1.2;
}

.dialog-subtitle {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  line-height: 1.4;
}

/* 表单样式 */
.task-form {
  padding: 24px;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f2f5;
}

.section-icon {
  width: 20px;
  height: 20px;
  color: #409eff;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

/* URL输入框 */
.url-input :deep(.el-input__wrapper) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.url-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.url-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 文件名输入框 */
.filename-input :deep(.el-input__wrapper) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.filename-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.filename-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 路径输入组 */
.path-input-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.path-input {
  flex: 1;
}

.path-input :deep(.el-input__wrapper) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.path-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.path-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.select-btn {
  padding: 12px 20px;
  border-radius: 8px;
  font-weight: 500;
  white-space: nowrap;
}

/* 数字输入组 */
.number-input-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.number-input {
  width: 180px;
}

.number-input :deep(.el-input__wrapper) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.number-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.number-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.input-unit {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

/* 开关样式 */
.custom-switch {
  margin-right: 12px;
}

.custom-switch :deep(.el-switch__core) {
  border-radius: 12px;
}

/* 提示信息 */
.form-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.form-tip .el-icon {
  font-size: 14px;
  color: #409eff;
}

/* 对话框底部 */
.dialog-footer {
  background: #fafafa;
  border-top: 1px solid #e4e7ed;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-left {
  display: flex;
  gap: 12px;
}

.footer-right {
  display: flex;
  gap: 12px;
}

.reset-btn {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  color: #f56c6c;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s;
}

.reset-btn:hover {
  background: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.cancel-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s;
}

.submit-btn {
  background: #409eff;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

/* 方法选择器样式 */
.method-select {
  width: 100%;
}

.option-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.option-title {
  font-weight: 500;
  color: #303133;
}

.option-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .new-task-dialog {
    width: 95vw !important;
    margin: 0 auto;
  }
  
  .dialog-header {
    padding: 20px;
  }
  
  .task-form {
    padding: 20px;
  }
  
  .path-input-group,
  .number-input-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .path-input,
  .number-input {
    width: 100%;
  }
  
  .select-btn {
    width: 100%;
  }
  
  .method-select {
    width: 100%;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .footer-left,
  .footer-right {
    justify-content: center;
  }
}
</style> 
